package com.heima.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.comment.dto.*;
import com.heima.comment.entity.ApComment;
import com.heima.comment.entity.ApCommentRepay;
import com.heima.comment.entity.ApCommentRepayLike;
import com.heima.comment.entity.UpdateCommentMessage;
import com.heima.comment.feign.ArticleFeign;
import com.heima.comment.feign.UserFeign;
import com.heima.comment.mongo.IApCommentRepayRepository;
import com.heima.comment.service.IAuditService;
import com.heima.comment.service.ICommentRepayService;
import com.heima.comment.vo.CommentRepayVo;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocalUtil;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author WSJ
 * @Date 2022-03-29-12:38
 * @Version 1.0 （版本号）
 */
@Service
public class CommentRepayServiceImpl implements ICommentRepayService {
    @Autowired
    private IAuditService auditService;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private MongoTemplate template;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    @Autowired
    private ArticleFeign articleFeign;
    @Override
    public ResponseResult save(CommentRepaySaveDto dto) {
        //保存对评论的评论
        //保存文章评论
        //必须登录后才能评论
        User user = AppThreadLocalUtil.get();
        if (user==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //判断评论内容不能为空白，不能超过140字
        if (dto==null|| StringUtils.isEmpty(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.COMMENT_NOT_NULL);
        }
        if (dto.getContent().length()>280) {
            return ResponseResult.errorResult(AppHttpCodeEnum.COMMENT_IS_TOO_LONG);
        }
        //判断评论是否关闭
        ApComment apComment = template.findById(new ObjectId(dto.getCommentId()), ApComment.class);
        ResponseResult<ApArticle> responseResult = articleFeign.getOperation(apComment.getEntryId());
        if (responseResult.getCode()== AppHttpCodeEnum.SUCCESS.getCode()) {
            ApArticle apArticle = responseResult.getData();
            if (!apArticle.getIsComment()) {
                return ResponseResult.errorResult(AppHttpCodeEnum.COMMENT_IS_CLOSE);
            }
        }
        //对文本内容做审核
        boolean audit = auditService.audit(dto.getContent());
        if (!audit) {
            return ResponseResult.errorResult(AppHttpCodeEnum.COMMENT_IS_FAILED);
        }
        //获取评论者头像
        ResponseResult<ApUser> userFeignImage = userFeign.findImage(user.getId());
        ApUser apUser=null;
        if (userFeignImage.getCode()== AppHttpCodeEnum.SUCCESS.getCode()) {
            apUser = userFeignImage.getData();
        }
        //构建评论对象
        ApCommentRepay comment = new ApCommentRepay();
        comment.setAuthorId(apUser.getId());
        comment.setAuthorName(apUser.getName());
        comment.setContent(dto.getContent());
        comment.setCreatedTime(new Date());
        comment.setEntryId(dto.getCommentId());
        comment.setFlag(0);
        comment.setReply(0);
        comment.setLikes(0L);
        comment.setType(0);
        comment.setImage(apUser.getImage());
        //保存评论
        template.save(comment);
        //发送kafka
        UpdateCommentMessage message = new UpdateCommentMessage();
        message.setAdd(1);
        message.setCommentId(dto.getCommentId());
        message.setType(2);
        String jsonString = JSON.toJSONString(message);
        kafkaTemplate.send("comment_repay_score_topic", jsonString);
        //返回
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult load(CommentRepayDto dto) {
        //评论的评论列表
        //分页查询评论列表
        //构建查询条件
        Query query = new Query();
        query.addCriteria(Criteria.where("entryId").is(dto.getCommentId()));
        PageRequest pageRequest = PageRequest.of(dto.getPage().intValue()-1, dto.getSize(), Sort.Direction.DESC, "createdTime");
        query.with(pageRequest);
        List<ApCommentRepay> apComments = template.find(query, ApCommentRepay.class);
        //查询对评论是否点赞
        List<CommentRepayVo> voList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(apComments)) {
            for (ApCommentRepay apCommentRepay : apComments) {
                Query queryLike = new Query();
                queryLike.addCriteria(Criteria.where("commentRepayId").is(apCommentRepay.getId().toHexString()));
                ApCommentRepayLike apCommentRepayLike = template.findOne(queryLike, ApCommentRepayLike.class);
                //构建vo
                CommentRepayVo vo = new CommentRepayVo();
                BeanUtils.copyProperties(apCommentRepay,vo);
                if (apCommentRepayLike!=null) {
                    vo.setOperation(apCommentRepayLike.getOperation());
                }
                voList.add(vo);
            }
        }
        //返回
        return ResponseResult.okResult(voList);
    }

    @Override
    public ResponseResult like(CommentRepayLikeDto dto) {
        //点赞，取消点赞
        //必须登录后才能点赞
        User user = AppThreadLocalUtil.get();
        if (user==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //构建对象
        //查询是否存在记录
        Query query = new Query();
        query.addCriteria(Criteria.where("commentRepayId").is(dto.getCommentRepayId()));
        query.addCriteria(Criteria.where("authorId").is(user.getId()));
        ApCommentRepayLike commentLike = template.findOne(query, ApCommentRepayLike.class);
        if (commentLike==null) {
            //不存在，则保存
            commentLike = new ApCommentRepayLike();
            commentLike.setCommentRepayId(dto.getCommentRepayId());
            commentLike.setOperation(dto.getOperation().intValue());
            commentLike.setAuthorId(user.getId());
        }else {
            //存在，则修改
            commentLike.setOperation(dto.getOperation().intValue());
        }
        //保存
        template.save(commentLike);
        //发送kafka
        UpdateCommentMessage message = new UpdateCommentMessage();
        message.setAdd(dto.getOperation()==0?1:-1);
        message.setCommentId(dto.getCommentRepayId());
        message.setType(1);
        String jsonString = JSON.toJSONString(message);
        kafkaTemplate.send("comment_repay_score_topic", jsonString);
        //返回
        return ResponseResult.okResult();
    }
    @Autowired
    private IApCommentRepayRepository repository;
    @Override
    public ResponseResult delete(String commentRepayId) {
        //删除评论回复
        repository.deleteById(new ObjectId(commentRepayId));
        //删除评论点赞
        Query query = new Query();
        query.addCriteria(Criteria.where("commentRepayId").is(commentRepayId));
        template.remove(query,ApCommentRepayLike.class);
        //返回
        return ResponseResult.okResult();
    }
}
